package com.michaelbulava.TFS.ui.wizards.common.connect;

import com.intellij.ide.wizard.CommitStepException;
import com.michaelbulava.TFS.Messages;
import com.michaelbulava.TFS.ui.controls.workspaces.WorkspacesControl;
import com.michaelbulava.TFS.ui.framework.wizard.ExtendedWizardStep;
import com.michaelbulava.TFS.ui.wizards.common.IConnectWizard;
import com.microsoft.tfs.core.TFSTeamProjectCollection;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace;

import javax.swing.*;

/**
 * Created by mbulava on 6/22/2015.
 */
public class SelectWorkspaceWizardStep extends ExtendedWizardStep {
    public static final Object STEP_ID = new Object();

    private final IConnectWizard wizard;
    private final WorkspacesControl control;

    public SelectWorkspaceWizardStep(IConnectWizard parentWizard){
        super(Messages.getString("SelectWorkspaceWizardStep.Title"));
        this.wizard = parentWizard;
        control = new WorkspacesControl();
        control.addSelectedWorkspaceChangeListener(new WorkspacesControl.SelectedWorkspaceChangeListener() {
            @Override
            public void onSelectionChanged(Workspace newSelection) {
                fireStateChanged();
            }
        });
    }

    @Override
    public void _init(){
        control.refresh(wizard.getTeamProjectCollection());
        if (wizard.getWorkspace() != null)
            control.setSelected(wizard.getWorkspace());
    }

    @Override
    public Object getStepId() {
        return STEP_ID;
    }

    @Override
    public Object getNextStepId() {
        return wizard.getNextStepId(this);
    }

    @Override
    public Object getPreviousStepId() {
        return wizard.getPreviousStepId(this);
    }

    @Override
    public void commit(CommitType commitType) throws CommitStepException {
        if (commitType == CommitType.Next | commitType == CommitType.Finish)
            wizard.setWorkspace(control.getSelectedWorkspace());
    }

    @Override
    public boolean isComplete() {
        return (control.getSelectedWorkspace() != null);
    }

    @Override
    public JComponent getComponent() {
        return control;
    }

    @Override
    public JComponent getPreferredFocusedComponent() {
        return null;
    }
}
